package com.tang.service.impl;

import com.tang.dao.DayIndexDao;
import com.tang.dao.FoodDao;
import com.tang.entity.DayIndex;
import com.tang.entity.Food;
import com.tang.entity.TakeFood;
import com.tang.mapper.TakeFoodMapper;
import com.tang.service.TakeFoodService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.tang.service.DayIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务接口实现
 *
 * @author kancy
 * @since 2024-07-21 14:12:37
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DayIndexServiceImpl implements DayIndexService {
    private final DayIndexDao dayIndexDao;

    @Autowired
    TakeFoodMapper takeFoodMapper;

    @Autowired
    FoodDao foodDao;

    @Override
    @Scheduled(cron ="1 0 0 * * ? " )
    public void sum() {
        //十二点开始
        //每天凌晨启动该服务
        LocalDateTime timefinal=LocalDateTime.now();
        LocalDateTime timestart=timefinal.minusDays(1);
        List<TakeFood> takeFoodList= takeFoodMapper.getFoodByDay(timestart,timefinal);
        //循环遍历takefood一条  仅仅遍历当天的数值
        Map<Long,DayIndex> map=new HashMap<>();
        takeFoodList.forEach(takeFood -> {
            Double count=takeFood.getCount();
            Food food=foodDao.getById(takeFood.getFoodId());
            Double sugar=food.getSugar()*count/100;
            Double fat=food.getFat()*count/100;
            Double protein=food.getProtein()*count/100;
            Double caluli=food.getCalories()*count/100;
            DayIndex dayIndex= map.get(takeFood.getUserId());
            if(dayIndex==null){

                dayIndex.setUserId(takeFood.getUserId());
                dayIndex.setFat(fat);
                dayIndex.setProtein(protein);
                dayIndex.setCalories(caluli);
                dayIndex.setSugar(sugar);

            }
            else{
                dayIndex.setSugar(dayIndex.getSugar()+sugar);
                dayIndex.setCalories(dayIndex.getCalories()+caluli);
                dayIndex.setProtein(dayIndex.getProtein()+protein);
                dayIndex.setFat(dayIndex.getFat()+fat);
            }


            map.put(takeFood.getUserId(),dayIndex);
        });

        Collection<DayIndex> values = map.values();


        dayIndexDao.saveBatch(values);


    }
}